import qs from "qs"
import { Toast } from 'antd-mobile'
import _ from '../assets/utils'
//const baseURL = '/api'
//核心方法
const http = function http(config){
    if(!config) config = {}
    config = Object.assign({
        url:'',
        method:'GET',
        credentials:'include', //资源凭证:同源和跨域都可以
        headers:null,
        body:null,
        params:null,
        responseType:'json',
        signal:null
    },config)
    if(!config.url) throw new TypeError('url must be required')
    if(!config.headers) config.headers = {}
    if(!config.params) config.params = null

    let {url,method,credentials,headers,body,params,responseType,signal} = config
    if(params){
        url += `${url.includes('?') ? '' : '?'}${qs.stringify(params)}` //''替换'&'
    }
    //处理请求主体信息∶按照我们后台要求，如果传递的是一个普通对象，我们要把其设置为urlencoded格式「设置请求头!
    if(body && !(body instanceof FormData)){ //是否为 FormData 类型
        headers['Content-Type'] = 'application/x-www-form-urlencoded'
        body = qs.stringify(body)
    }
    /* if(body && body instanceof FormData){
        headers['Content-Type'] = 'multipart/form-data'
    } */

    //let token = localStorage.getItem('tk')
    let token = _.storage.get('tk')
    //token于http请求的列表
    const safeList = ['/user_info','/user_update','/store','/store_remove','/store_list'] //user_info
    if(token){ 
        const reg = /\/api(\/[^#?]+)/,
            [,$1] = reg.exec(url) || []
        let isSafe = safeList.some(item => {
            return $1 === item
        })
        if(isSafe) headers['Authorization'] = token
    }

    //发送请求
    method = method.toUpperCase()
    config = {
        method,
        credentials,
        headers,
        caches:'no-cache',
        signal
    }
    if(/^(POST|PUT|PATCH)$/i.test(method) && body) config.body = body

    return fetch(url,config)
      .then(response => {
        let {status,statusText}  = response;
        if(/^(2|3)\d{2}$/.test(status)){
            let result;
            switch(responseType.toLowerCase()){
                case 'test':
                    result = response.text()
                    break;
                case 'arraybuffer':
                    result = response.arrayBuffer()
                    break;
                case 'blob':
                    result = response.blob()
                    break;
                default:
                    result = response.json()
            }
            return result;
        }
        return Promise.reject({
            code:-999,
            status,
            statusText
        })
      })
      .catch(reason => {
        Toast.show({
            icon:'fail',
            content:'网络繁忙，请稍后再试'
        })
        return Promise.reject(reason) 
      })
}
//快捷方法
/* ['GET','HEAD','DELETE','OPTIONS'].forEach(item => {
    http[item.toLowerCase()] = function(url,config){
        if(!config) config = {}
        config['url'] = url
        config['method'] = item
        return http(config)
    }
}) */
let arr1 = ['GET','HEAD','DELETE','OPTIONS']
arr1.forEach(item => {
    http[item.toLowerCase()] = function(url,config){
        if(!config) config = {}
        config['url'] = url
        config['method'] = item
        return http(config)
    }
})
let arr2 = ['POST','PUT','PATCH']
arr2.forEach(item => {
    http[item.toLowerCase()] = function(url,body,config){
        if(!config) config = {}
        config['url'] = url
        config['method'] = item
        config['body'] = body
        return http(config)
    }
})

export default http

